package com.yzdmw.toutiao.wheeldisk.ui;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.NavController;
import androidx.navigation.NavDirections;
import androidx.navigation.Navigation;
import androidx.navigation.fragment.NavHostFragment;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.snackbar.Snackbar;
import com.yzdmw.toutiao.MainActivity;
import com.yzdmw.toutiao.R;
import com.yzdmw.toutiao.databinding.WheeldiskFragmentBinding;
import com.yzdmw.toutiao.model.News;

import org.jetbrains.annotations.NotNull;

public class WheeldiskFragment extends Fragment {
    public static final String TAG = "WheeldiskFragment";
    private static final boolean DEBUG=false;
    private WheeldiskFragmentBinding binding;
    private WheeldiskViewModel mViewModel;
    private WheeldiskAdapter wheeldiskAdapter;
    private ProgressBar loadingProgressBar;
    private String newsType = "all";

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        binding = WheeldiskFragmentBinding.inflate(inflater,container,false);
        return binding.getRoot();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    public void onViewCreated(@NonNull @NotNull View view, @Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        NavController navController = NavHostFragment.findNavController(this);

        mViewModel = new ViewModelProvider(navController.getViewModelStoreOwner(R.id.main_nav))
                .get(WheeldiskViewModel.class);

        loadingProgressBar = binding.loading;
        final RecyclerView recyclerView = binding.recyclerView;

        setRecyclerView(recyclerView);

        setViewModelObserver();
        refresh(newsType, true);
        ((MainActivity) getActivity()).enableSlidingMenu();
    }
    private static int REFRESHING  = 0x1;
    private static int REFRESHABLE = 0x2;
    private int refreshState = REFRESHABLE;
    private synchronized void refresh(String type, boolean clear) {
        if (refreshState == REFRESHABLE) {
            refreshState = REFRESHING;
            loadingProgressBar.setVisibility(View.VISIBLE);
            mViewModel.refreshNews(type, clear);
        }
    }

    private void setViewModelObserver() {
        mViewModel.refreshError().observe(getViewLifecycleOwner(), err -> {
            loadingProgressBar.setVisibility(View.GONE);
            refreshState = REFRESHABLE;
            if (err == null) {
                wheeldiskAdapter.notifyDataSetChanged();
            } else {
                Snackbar.make(requireView(),err,Snackbar.LENGTH_SHORT).show();
            }
        });
    }

    private void setRecyclerView(RecyclerView recyclerView) {
        // 用layoutmanager管理布局
        recyclerView.setLayoutManager(new WheeldiskLayoutManager());

        // 用adapter处理点击和滚动加载
        wheeldiskAdapter = new WheeldiskAdapter(getContext(), mViewModel.news, new WheeldiskAdapter.MyListener() {
            @Override public void onItemClick(News item) {
                navigateToDetail(item.title);
            }
            @Override public void onPreLoad() {
                if (DEBUG) Log.d(TAG,"preload");
                refresh(newsType,false);
            }
        });
        recyclerView.setAdapter(wheeldiskAdapter);

        // 用snapHelper来对齐
        WheeldiskSnapHelper snapHelper = new WheeldiskSnapHelper();
        snapHelper.attachToRecyclerView(recyclerView);

        // 用ItemTouchHelper来拖拽
        ItemTouchHelper itemTouchHelper = createItemTouchHelper();
        itemTouchHelper.attachToRecyclerView(recyclerView);
    }
    private ItemTouchHelper createItemTouchHelper() {
        return new ItemTouchHelper(new ItemTouchHelper.Callback() {
            @Override
            public int getMovementFlags(@NotNull RecyclerView recyclerView, @NotNull RecyclerView.ViewHolder viewHolder) {
                return makeMovementFlags(ItemTouchHelper.UP|ItemTouchHelper.DOWN|ItemTouchHelper.LEFT|ItemTouchHelper.RIGHT,0);
            }

            @Override
            public boolean onMove(@NotNull RecyclerView recyclerView, @NotNull RecyclerView.ViewHolder viewHolder, @NotNull RecyclerView.ViewHolder target) {
                //当拖拽的viewHolder的Position
                int fromPosition = viewHolder.getAdapterPosition();
                //当前拖拽到的item的viewHolder
                int toPosition = target.getAdapterPosition();
                mViewModel.itemMove(fromPosition,toPosition);
                wheeldiskAdapter.notifyItemMoved(fromPosition, toPosition);
                return true;
            }

            @Override
            public boolean isLongPressDragEnabled() {
                return true;
            }

            @Override
            public void onSwiped(@NonNull @NotNull RecyclerView.ViewHolder viewHolder, int direction) { }

            @Override
            public void onSelectedChanged(RecyclerView.ViewHolder viewHolder, int actionState) {
                if (actionState != ItemTouchHelper.ACTION_STATE_IDLE) {
                    viewHolder.itemView.setAlpha(0.5F);
                }
                super.onSelectedChanged(viewHolder, actionState);
            }

            @Override
            public void clearView(@NotNull RecyclerView recyclerView, @NotNull RecyclerView.ViewHolder viewHolder) {
                super.clearView(recyclerView, viewHolder);
                viewHolder.itemView.setAlpha(1F);
                wheeldiskAdapter.notifyDataSetChanged(); //完成拖动后刷新适配器，这样拖动后删除就不会错乱
            }
        });
    }

    private void navigateToDetail(String articleID) {
        NavDirections navDirections = WheeldiskFragmentDirections.navigateToDetail()
                .setArticleID(articleID);
        Navigation.findNavController(requireView()).navigate(navDirections);
    }
}